package com.gofaraway.service.student.leetCodeV2.滑动窗口;

import java.util.HashMap;

/**
 * https://leetcode.cn/problems/longest-substring-without-repeating-characters/?envType=study-plan-v2&envId=top-100-liked
 *
 * @author ChenPeng
 * @date 2025/7/4 15:03
 */
public class 无重复字符的最长子串 {

    public int lengthOfLongestSubstring(String s) {
        HashMap<Character, Integer> map = new HashMap<>();
        int maxLength = 0;
        int left = 0;

        for (int i = 0; i < s.length(); i++) {
            char c = s.charAt(i);
            //fixme 关键点：如果字典里面存在当前字符，且上一次出现的改字符在当前窗口内 则左边界跳跃 至上一次出现该字符的next index
            if (map.containsKey(c)) {
                if (map.get(c) >= left && map.get(c) <= i) {
                    Integer nextIndex = map.get(c);
                    left = nextIndex + 1;
                } else if (map.get(c) < left) {
                    left = left;
                }
            }
            //更新 maxLength
            maxLength = Math.max(maxLength, i - left +1);
            map.put(c, i);
        }
        return maxLength;
    }
}
